package com.example.callcenter.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * 统一的RabbitMQ配置类（修正类名从RabbitConfig→RabbitMQConfig）
 */
@Configuration
public class RabbitMQConfig {
    // 短信发送队列配置
    public static final String SMS_EXCHANGE = "sms.exchange";
    public static final String SMS_QUEUE = "sms.queue";
    public static final String SMS_ROUTING_KEY = "sms.send";

    // 任务分发队列配置
    public static final String TASK_EXCHANGE = "task.distribute.exchange";
    public static final String TASK_QUEUE = "task.distribute.queue";
    public static final String TASK_ROUTING_KEY = "task.distribute";

    // 死信队列配置
    public static final String DLX_EXCHANGE = "dlx.exchange";
    public static final String DLX_QUEUE = "dlx.queue";
    public static final String DLX_ROUTING_KEY = "#";

    // JSON消息转换器配置（核心解决代码）
    @Bean
    public Jackson2JsonMessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(messageConverter());
        rabbitTemplate.setMandatory(true);
        return rabbitTemplate;
    }

    // ============================ 短信队列 ============================
    @Bean
    public DirectExchange smsExchange() {
        return ExchangeBuilder.directExchange(SMS_EXCHANGE).durable(true).build();
    }

    @Bean
    public Queue smsQueue() {
        return QueueBuilder.durable(SMS_QUEUE)
                .withArgument("x-dead-letter-exchange", DLX_EXCHANGE)
                .withArgument("x-message-ttl", 60000) // 1分钟过期
                .build();
    }

    @Bean
    public Binding smsBinding() {
        return BindingBuilder.bind(smsQueue()).to(smsExchange()).with(SMS_ROUTING_KEY);
    }

    // ============================ 任务分发队列 ============================
    @Bean
    public DirectExchange taskExchange() {
        return ExchangeBuilder.directExchange(TASK_EXCHANGE).durable(true).build();
    }

    @Bean
    public Queue taskQueue() {
        return QueueBuilder.durable(TASK_QUEUE)
                .withArgument("x-dead-letter-exchange", DLX_EXCHANGE)
                .withArgument("x-message-ttl", 60000) // 1分钟过期
                .build();
    }

    @Bean
    public Binding taskBinding() {
        return BindingBuilder.bind(taskQueue()).to(taskExchange()).with(TASK_ROUTING_KEY);
    }

    // ============================ 死信队列 ============================
    @Bean
    public DirectExchange dlxExchange() {
        return ExchangeBuilder.directExchange(DLX_EXCHANGE).durable(true).build();
    }

    @Bean
    public Queue dlxQueue() {
        return QueueBuilder.durable(DLX_QUEUE).build();
    }

    @Bean
    public Binding dlxBinding() {
        return BindingBuilder.bind(dlxQueue()).to(dlxExchange()).with(DLX_ROUTING_KEY);
    }

    // ============================ 消费者容器工厂 ============================
    @Autowired
    @Qualifier("messageExecutor")
    private ThreadPoolTaskExecutor messageExecutor;

    @Bean
    public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(ConnectionFactory connectionFactory) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setTaskExecutor(messageExecutor); // 使用自定义线程池
        factory.setConcurrentConsumers(2); // 并发消费者数量
        factory.setMaxConcurrentConsumers(6); // 最大并发消费者
        factory.setAcknowledgeMode(AcknowledgeMode.MANUAL); // 手动ACK

        factory.setDefaultRequeueRejected(false);
        factory.setMissingQueuesFatal(false); // 防止队列不存在时应用启动失败
        factory.setIdleEventInterval(60000L); // 空闲事件间隔
        factory.setMessageConverter(messageConverter()); // 消费者使用JSON转换器
        return factory;
    }
}